package com.inspector.app.ui.flight.maplayer;


import android.content.DialogInterface;
import android.graphics.Rect;
import android.os.Bundle;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.TouchDelegate;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.ImageView;

import androidx.annotation.NonNull;
import androidx.fragment.app.DialogFragment;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.RecyclerView;
import com.inspector.app.R;
import com.inspector.app.di.util.UI;
import com.inspector.app.ui.flight.FlightFragment;
import com.mapsforge.map.EfbMap;
import com.mapsforge.map.vtm.VtmEfbMap;

import org.jetbrains.annotations.NotNull;

import java.util.ArrayList;
import java.util.Arrays;

import com.inspector.app.util.ConstantUtil;
import com.inspector.app.util.SharedPreferencesUtils;



/**
 * [切换地图图层]
 */
public class SwitchMapLayerFragment extends DialogFragment {


    private View itemMapLayer;
    private ImageView itemIVClose;
    private RecyclerView itemRV;

    private SwitchMapLayerAdapter layerAdapter;
    private ArrayList<SwitchMapLayerAdapter.SwitchItem> mList = new ArrayList<>();

    public static String mapLayerType = "SwitchMapLayer_Type";
    private String[] textStrings = {
            "天地图地形图", "天地图矢量图", "天地图影像图", "离线地形图", "离线矢量图", "离线卫星图"};//, "天地图三维图"

    private Integer[] imgSrc = {
            R.mipmap.map_t_dixingtu, R.mipmap.map_t_shiliangtu, R.mipmap.map_t_yingxingtu,
            R.mipmap.map_dixingtu, R.mipmap.map_shiliangtu, R.mipmap.map_weixingtu};//, R.mipmap.map_t_sanweitu

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setStyle(STYLE_NO_TITLE, R.style.airport_dialog_style);
    }

    @Override
    public void onStart() {
        super.onStart();

        //[根据view设置当前dialog位置 高度等]
        initAttrs();
    }

    private void initAttrs() {
        Window window = getDialog() != null ? getDialog().getWindow() : null;
        if (locationView == null || window == null) return;
        int[] location = new int[2];
        locationView.getLocationOnScreen(location);
        int x = location[0];
        int y = location[1];

        //[设置弹窗位置]
        WindowManager.LayoutParams params = window.getAttributes();
//        params.x = (int) (x + locationView.getWidth() + UI.INSTANCE.dpToPx(15));
        params.y = y + UI.INSTANCE.getStatusBarHeight(requireActivity());
        window.setAttributes(params);

//        window.setGravity(Gravity.START | Gravity.TOP);
        window.setGravity(Gravity.CENTER_HORIZONTAL | Gravity.TOP);


        //[设置弹窗宽高 根据设计图百分比]
//        int width = ScreenUtils.getScreenWidth(requireContext()) * 346 / 533;
//        int height = ScreenUtils.getScreenHeight(requireContext()) * 263 / 853;
        int width = UI.INSTANCE.dpToPx(346);
        int height = UI.INSTANCE.dpToPx(263);
        window.setLayout(width, height);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View inflate = inflater.inflate(R.layout.maplayer_switch, container, false);
        setupView(inflate);

        int vectorLayerIndex = Arrays.asList(EfbMap.MapType.values()).indexOf(EfbMap.MapType.Vector); //[默认 矢量图层]
        int mapLayerIndex = SharedPreferencesUtils.getInt(ConstantUtil.USERID, ConstantUtil.MAP_LAYER_TYPE, vectorLayerIndex);

        notifyByPosition(EfbMap.MapType.values()[mapLayerIndex]);
        return inflate;
    }



    private void setupView(View rootView) {
        itemMapLayer = rootView.findViewById(R.id.itemMapLayer);
        itemIVClose = rootView.findViewById(R.id.itemIVClose);
        itemRV = rootView.findViewById(R.id.itemRV);

        layerAdapter = new SwitchMapLayerAdapter(mList, (view, item) -> {
            Fragment parentFragment = getParentFragment();
            if (parentFragment instanceof FlightFragment) {
                EfbMap mEfbMap = ((FlightFragment) parentFragment).getEfbMap();
                if (mEfbMap instanceof VtmEfbMap) {
                    if (((VtmEfbMap) mEfbMap).needDownload(item.mapType)) {
                        UI.INSTANCE.displayTopSnackBar(requireActivity(), view, "当前图层需要下载");
                        // TODO: 2024/7/17 [提醒弹窗]
//                        AccountManager.INSTANCE.showMapFileCheckDialog(requireContext());

                        return;
                    }
                }
            }

            notifyByPosition(item.mapType);
            dismissAllowingStateLoss();

            //[回调处理]
            if (listener != null) {
                listener.onItemClick(view, item);
            }
        });
        itemRV.setAdapter(layerAdapter);

        int dp7 = UI.INSTANCE.dpToPx(7);
        int dp14 = UI.INSTANCE.dpToPx(14);
        itemRV.addItemDecoration(new RecyclerView.ItemDecoration() {
            @Override
            public void getItemOffsets(Rect outRect, View view, RecyclerView parent, RecyclerView.State state) {
                super.getItemOffsets(outRect, view, parent, state);
                outRect.set(dp7, 0, dp7, dp14);
            }
        });

        //[扩大点击区域]
        expandTouchArea(itemMapLayer, itemIVClose, 100);
        itemIVClose.setOnClickListener(v -> {
            dismissAllowingStateLoss();
        });
    }


    private void notifyByPosition(EfbMap.MapType clickType) {
        for (int i = 0; i < textStrings.length; i++) {
            mList.add(new SwitchMapLayerAdapter.SwitchItem(textStrings[i], imgSrc[i], EfbMap.getMapTypeByIndex(i),clickType));
        }
        layerAdapter.notifyDataSetChanged();

        int mapLayerIndex = Arrays.asList(EfbMap.MapType.values()).indexOf(clickType);
        SharedPreferencesUtils.put(ConstantUtil.USERID, ConstantUtil.MAP_LAYER_TYPE, mapLayerIndex);
    }

    @Override
    public void onDismiss(@NonNull @NotNull DialogInterface dialog) {
        super.onDismiss(dialog);
        //[点击背景能关闭 回调刷新按钮状态]
        if (listener != null) {
            listener.onItemClick(null, null);
        }
    }

    public boolean isShowing() {
        return getDialog()!=null && getDialog().isShowing();
    }


    //[根据view设置当前dialog位置]
    private static View locationView;

    public static SwitchMapLayerAdapter.OnItemClickListener listener;

    public static SwitchMapLayerFragment create(View switchView, SwitchMapLayerAdapter.OnItemClickListener onItemClickListener) {
        locationView = switchView;
        listener = onItemClickListener;
        return new SwitchMapLayerFragment();
    }


    //[扩大点击区域]
    public static void expandTouchArea(final View bigView, final View smallView, final int extraPadding) {
        bigView.post(new Runnable() {
            @Override
            public void run() {
                Rect rect = new Rect();
                smallView.getHitRect(rect);
                rect.top -= extraPadding;
                rect.left -= extraPadding;
                rect.right += extraPadding;
                rect.bottom += extraPadding;
                bigView.setTouchDelegate(new TouchDelegate(rect, smallView));
            }
        });
    }
}
